package org.example.dao;

import kotlin.jvm.Throws;
import org.example.pojo.MessageCreate;
import org.example.pojo.Publish;
import org.example.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MessageDao {
    public List<MessageCreate> messageCreates(String username) throws Exception{
        //获得数据库链接
        Connection connection = JDBCUtils.getConnection();
        String sql = "select * from message where username=?";
        //使用PreparedStatement执行SQL语句可以防止SQL注入
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,username);
        ResultSet rs = ps.executeQuery();
        //将结果集封装到集合
        List<MessageCreate> list = new ArrayList<>();
        while (rs.next()) {
            MessageCreate messageCreate=new MessageCreate(
                    rs.getString("username"),
                    rs.getString("password"),
                    rs.getString("send-time"),
                    rs.getString("getter"),
                    rs.getString("get-time"),
                    rs.getString("content"));
            list.add(messageCreate);
        }
        return list;
    }

    public void insertMessage(String username,String password,String settime,String getter,String gettime,String content) throws SQLException {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into message(message.username,message.password,message.`send-time`,message.getter,message.`get-time`,message.content) values (?,?,?,?,?,?)";
        //使用PreparedStatement执行SQL语句可以防止SQL注入
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,username);
        ps.setString(2,password);
        ps.setString(3,settime);
        ps.setString(4,getter);
        ps.setString(5,gettime);
        ps.setString(6,content);
        // 直接调用executeUpdate()，不要传递SQL字符串
        ps.executeUpdate();

        // 关闭资源（通常在实际应用中会放在一个finally块中）
        ps.close();
        connection.close();
    }
}
